package com.dyw.spzx.manager.service.lmpl;

import com.alibaba.fastjson.JSON;
import com.dyw.spzx.common.excepiton.GuiguException;
import com.dyw.spzx.manager.mapper.SysUserMapper;
import com.dyw.spzx.manager.mapper.SysUserRoleMapper;
import com.dyw.spzx.manager.service.SysUserRoleService;
import com.dyw.spzx.manager.service.SysUserService;
import com.dyw.spzx.model.dto.system.AssginRoleDto;
import com.dyw.spzx.model.dto.system.LoginDto;
import com.dyw.spzx.model.dto.system.SysUserDto;
import com.dyw.spzx.model.entity.system.SysUser;
import com.dyw.spzx.model.vo.common.ResultCodeEnum;
import com.dyw.spzx.model.vo.system.LoginVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;


    // 用户登录
    @Override
    public LoginVo login(LoginDto loginDto) {
        // 验证 验证码是否正确
        String captcha = loginDto.getCaptcha();
        String codeKey = loginDto.getCodeKey();
        // 判断验证码是否为空
        if (captcha == null) {
            throw new GuiguException(ResultCodeEnum.LOGIN_ERROR_CAPTCHA);
        }
        // 判断验证码是否一致
        String codeValue = redisTemplate.opsForValue().get("user:login:validatecode:" + codeKey);
        if (codeValue == null) {
            throw new GuiguException(ResultCodeEnum.LOGIN_CAPTCHA_OVERDUE);
        }
        if (!codeValue.equals(captcha)) {
            throw new GuiguException(ResultCodeEnum.LOGIN_CAPTCHA_MISTAKEN);
        }

        // 验证通过删除Redis中的数据
        redisTemplate.delete("user:login:validatecode:" + codeKey);


        // 根据用户名查询用户
        String userName = loginDto.getUserName();
        SysUser sysUser = sysUserMapper.selectUserByUserName(userName);
        if (sysUser == null) {
            // throw new RuntimeException("用户不存在");
            throw new GuiguException(ResultCodeEnum.LOGIN_ERROR_USER);
        }
        // 验证密码是否正确
        String dtoPassword = loginDto.getPassword();
        String password = DigestUtils.md5DigestAsHex(dtoPassword.getBytes());
        if (!sysUser.getPassword().equals(password)) {
            // throw new RuntimeException("密码有误");
            throw new GuiguException(ResultCodeEnum.LOGIN_ERROR);
        }
        // 生成令牌，保存数据到Redis中
        String token = UUID.randomUUID().toString().replace("-", "");
        String jsonString = JSON.toJSONString(sysUser);
        redisTemplate.opsForValue().set("user:login" + token, jsonString, 1, TimeUnit.DAYS);
        // 构建响应结果对象
        LoginVo loginVo = new LoginVo();
        loginVo.setToken(token);

        // 返回
        return loginVo;
    }

    @Override
    public SysUser getUserInfo(String token) {
        String userJson = redisTemplate.opsForValue().get("user:login" + token);
        SysUser sysUser = JSON.parseObject(userJson, SysUser.class);
        return sysUser;
    }

    // 退出登录
    @Override
    public void logout(String token) {
        redisTemplate.delete("user:login" + token);
    }

    // 查询用户列表
    @Override
    public PageInfo<SysUser> findSysUserByPage(SysUserDto sysUserDto, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<SysUser> sysUserList = sysUserMapper.findSysUserByPage(sysUserDto);
        PageInfo<SysUser> userPageInfo = new PageInfo<>(sysUserList);
        return userPageInfo;
    }

    // 保存用户信息
    @Override
    public void saveSysUser(SysUser sysUser) {

        if (sysUser.getUsername() == null || sysUser.getPassword() == null || sysUser.getName() == null) {
            throw new GuiguException(ResultCodeEnum.USER_CANNOT_EMPTY_ERROR);
        }


        // 根据输入的用户名查询用户是否存在
        String username = sysUser.getUsername();
        SysUser dbsysUser = sysUserMapper.selectUserByUserName(username);
        if (dbsysUser != null) {
            throw new GuiguException(ResultCodeEnum.USER_NAME_IS_EXISTS);
        }
        // 对用户密码进行加密
        String password = sysUser.getPassword();
        String md5Password = DigestUtils.md5DigestAsHex(password.getBytes());
        sysUser.setPassword(md5Password);
        sysUser.setStatus(1);
        sysUserMapper.insertSysUser(sysUser);
    }

    // 修改用户信息
    @Override
    public void updateSysUser(SysUser sysUser) {
        sysUserMapper.updateSysUser(sysUser);
    }

    // 删除用户信息
    @Override
    public void deleteById(Integer userId) {
        sysUserMapper.deleteById(userId);
    }

    @Override
    public void doAssign(AssginRoleDto assginRoleDto) {
        // 删除用户之前所对应的角色数据
        sysUserRoleMapper.deleteRoleByUserId(assginRoleDto.getUserId());
        // 分配新的角色给用户
        List<Long> roleIdList = assginRoleDto.getRoleIdList();
        roleIdList.forEach(roleId -> {
            sysUserRoleMapper.doAssign(assginRoleDto.getUserId(), roleId);
        });


    }
}
